//
//  YFAppVersionUpdate.m
//  QuanJieShopProject
//
//  Created by apple on 2018/4/26.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "YFAppVersionUpdate.h"
#import "YFGlobalTool.h"
#import "AFNetworking.h"
@interface YFAppVersionUpdate()

@end

@implementation YFAppVersionUpdate

#pragma mark -- 单例
+ (instancetype)sharedInstance {
    static YFAppVersionUpdate *_update = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _update = [[YFAppVersionUpdate alloc] init];
    });
    return _update;
}

- (void)setAppID:(NSString *)appID {
    _appID = appID;
    
    // 判断id的长度是否为10位
    if (appID.length != 10) return;
    
    NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@", appID];
    
    
    NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]] returningResponse:nil error:nil];
    
    if (response == nil){
        NSLog(@"你没有连接网络哦");
        return;
    }
    
    NSError *error;
    NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    NSLog(@"appInfoDic = %@", appInfoDic);
    //    if (error){
    ////        NSLog(@"hsUpdateAppError:%@",error);
    //        return;
    //    }
    NSArray *array = appInfoDic[@"results"];
    NSDictionary *dic = array[0];
    NSString *updateVersion = dic[@"version"];
    //    NSLog(@"版本更新 dic = %@", dic);
    //获取当前设备中应用的版本号
    NSString *currentVersion = [YFGlobalTool appVersion];
    //    if (currentVersion.length == 0) {
    //        return;
    //    }
    
    self.currentVersion = currentVersion;
    self.updateVersion = updateVersion;
    self.appName = dic[@"trackName"];
    self.title = @"更新提示";
    self.message = [NSString stringWithFormat:@"《%@》有新版本啦!", self.appName];
    self.releaseNotes = dic[@"releaseNotes"];
    NSLog(@"currentVersion = %@, updaVersion = %@", self.currentVersion, self.updateVersion);
//    self.currentVersion = @"1.2.9";
    
    // 判断商店是否有更新版本
    if ([self.updateVersion compare:self.currentVersion options:NSNumericSearch] == NSOrderedDescending) {
        self.isUpdate = YES;
        
        // 同步请求
        NSString *updateUrl = @"http://api.quanjieshop.com/api/index.php/home/index/updateVesion?type=ios";
        NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:updateUrl]] returningResponse:nil error:nil];
        
        NSError *error;
        NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        if (appInfoDic && [appInfoDic isKindOfClass:[NSDictionary class]]) {
            NSDictionary *data = appInfoDic[@"data"];
            NSNumber *isForceUpdate = data[@"type"];
            if (isForceUpdate.intValue == 0) {
                self.isForceToUpdate = NO;
            }else {
                self.isForceToUpdate = YES;
            }
        }
        
        //        // 判断是否强制更新
        //        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        //        [dict setObject:@"ios" forKey:@"type"];
        //        [WWNetRequest fetchForceToUpdateWithParameters:dict success:^(id response) {
        //            NSLog(@"强制更新 response = %@", response);
        //
        //        } failure:^(NSDictionary *error) {
        //            NSLog(@"强制更新 error = %@", error);
        //        }];
        
        
    }else {
        self.isUpdate = NO;
    }
    
}

// 目前只支持这一种样式
- (void)showAlertView {
    
    if (self.isUpdate) {
        
        if (self.isShowing) {  // 避免弹框重复
            return;
        }
        self.isShowing = YES;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:self.title message:self.message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我要更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *loadUrlStr = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id%@", self.appID];
            NSURL *url = [NSURL URLWithString:loadUrlStr];
            [[UIApplication sharedApplication] openURL:url];
            self.isShowing = NO;
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"暂不更新" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            self.isShowing = NO;
        }];
        
        if (self.isForceToUpdate) {  // 强制更新
            
        }else { // 一般更新
            [alertController addAction:cancelAction];
        }
        [alertController addAction:okAction];
        
        
        UIWindow  *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        alertWindow.rootViewController = [[UIViewController alloc] init];
        alertWindow.windowLevel = UIWindowLevelAlert + 1;
        [alertWindow makeKeyAndVisible];
        [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
        
    }
}



// 暂时写这里
#pragma mark -- 13.跳转到应用页面
+ (void)gotoAPPStore:(NSString *)appid{
    NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%@",appid];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
#pragma mark -- 14.跳转到评价页面
+ (void)gotoCommentAPP:(NSString *)appid{
    NSString *str = [NSString stringWithFormat: @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id;=%@",
                     appid ];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
@end
